package android.slc.andserver_flutter2.andserver;

import android.content.Context;
import android.slc.andserver_flutter2.andserver.config.AppWebConfig;
import android.util.Log;

import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.util.concurrent.TimeUnit;

public class ServerManager {
    private static volatile ServerManager INSTANCE;

    private final Server mServer;

    public static ServerManager getInstance(Context context) {
        if (INSTANCE == null) {
            synchronized (ServerManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new ServerManager(context);
                }
            }
        }
        return INSTANCE;
    }

    /**
     * Create server.
     */
    private ServerManager(Context context) {
        AppWebConfig.rootPath = context.getCacheDir().getAbsolutePath();
        mServer = AndServer.webServer(context).port(8080).timeout(15, TimeUnit.SECONDS).listener(new Server.ServerListener() {
            @Override
            public void onStarted() {
                Log.w("AndServer", "The server started successfully.");
            }

            @Override
            public void onStopped() {
                Log.w("AndServer", "The server has stopped.");
            }

            @Override
            public void onException(Exception e) {
                Log.w("AndServer", "An exception occurred while the server was starting.");
                Log.w("AndServer", e);
            }
        }).build();
    }

    /**
     * Start server.
     */
    public void startServer() {
        if (mServer.isRunning()) {
            Log.w("AndServer", "The server is already up.");
        } else {
            mServer.startup();
        }
    }

    /**
     * Stop server.
     */
    public void stopServer() {
        if (mServer.isRunning()) {
            mServer.shutdown();
        } else {
            Log.w("AndServer", "The server has not started yet.");
        }
    }
}